//
//  OAuthViewController.swift
//  MAGweibo
//
//  Created by MagicaL on 15/8/2.
//  Copyright © 2015年 MagicaL. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController,UIWebViewDelegate {

    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        webView.delegate = self
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    /// 关闭界面
    func close (){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 加载授权页面
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthUrl()))
        
    }
   
    // MARK: - webView 代理方法
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    /**
        1. 如果请求的 URL 包含回调地址 需要判断参数 否则 继续加载
        2. 如果请求参数中 包含code 可以从URL中 获得请求码
    */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
        if !urlString.hasPrefix(NetworkTools.sharedTools.redirectUri) { // 如果不是回调地址则继续加载
            return true
        }
        
        if let query = request.URL?.query where query.hasPrefix("code=") {
        
            // 从query中截取授权码
            let code = query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
            print(code)
            // 换取Token
            loadAccessToken(code)
        } else {
            close()
        }
        return false
    
    }
  
    private func loadAccessToken(code: String) {
        
        NetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil || result == nil {
                SVProgressHUD.showInfoWithStatus("网络不给力")
                
                // 延迟一段时间关闭
                let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
                dispatch_after(when, dispatch_get_main_queue()) {
                    self.close()
                }
                return
            }
            // 字典转模型
            
            
        }
        
    }
    
}


